package cn.virens.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import com.alibaba.fastjson.support.spring.FastjsonSockJsMessageCodec;

import cn.virens.web.components.websocket.WebSocketHandler;
import cn.virens.web.components.websocket.WebSocketHandshakeHandler;
import cn.virens.web.components.websocket.WebSocketHandshakeInterceptor;

@Configuration
@EnableWebSocket
public class SpringWebSocketConfig implements WebSocketConfigurer {

	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(webSocketHandler(), "/socket")//
				.addInterceptors(webSocketHandshakeInterceptor())//
				.setHandshakeHandler(webSocketHandshakeHandler())//
				.setAllowedOrigins("*");
	}

	@Bean
	public FastjsonSockJsMessageCodec fastjsonSockJsMessageCodec() {
		return new FastjsonSockJsMessageCodec();
	}

	@Bean
	public WebSocketHandler webSocketHandler() {
		return new WebSocketHandler();
	}

	@Bean
	public WebSocketHandshakeHandler webSocketHandshakeHandler() {
		return new WebSocketHandshakeHandler();
	}

	@Bean
	public WebSocketHandshakeInterceptor webSocketHandshakeInterceptor() {
		return new WebSocketHandshakeInterceptor();
	}
}
